package com.mib.reduce;

import java.io.*;
import java.util.Collections;

public class ReduceJre {
    public static boolean copy(String file1, String file2) {
        try {
            java.io.File file_in = new java.io.File(file1);
            java.io.File file_out = new java.io.File(file2);
            FileInputStream in1 = new FileInputStream(file_in);
            FileOutputStream out1 = new FileOutputStream(file_out);
            byte[] bytes = new byte[1024];
            int c;
            while ((c = in1.read(bytes)) != -1)
                out1.write(bytes, 0, c);
            in1.close();
            out1.close();
            return (true);
        } catch (Exception e) {
            System.out.println("Error!");
            return (false); //if fail then return false
        }
    }

    //读取路径,copy
    public static int dealClass(String needfile, String sdir, String odir) throws IOException {
        int sn = 0; //成功个数

        File usedclass = new File(needfile);
        if (usedclass.canRead()) {
            String line = null;
            LineNumberReader reader = new LineNumberReader(new InputStreamReader(new FileInputStream(usedclass), "UTF-8"));
            while ((line = reader.readLine()) != null) {
                if(line.contains("from") && line.contains("[Loaded")){
                    line = line.substring(0, line.indexOf("from")).trim();
                    line = line.substring(line.lastIndexOf("[Loaded") + 7).trim();

                    line = line.replaceAll("\\.", "\\\\");

                    File fdir = new File(line);
                    if (!fdir.exists())
                        fdir.mkdirs();
                    String sf = sdir + line + ".class";
                    String of = odir + line + ".class";
                    boolean copy_ok = copy(sf.trim(), of.trim());
                    if (copy_ok)
                        sn++;
                    else {
                        System.out.println(line);
                    }
                }
            }
        }
        return sn;
    }

    public static void main(String[] args) {
        String needfile = "D:\\MIB_Browser\\class.txt";
        String sdir = "";
        String odir = "D:\\MIB_Browser\\rt1\\";
        try {
            int sn = dealClass(needfile, sdir, odir);
            System.out.print(sn);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
